# encoding: utf-8
from flask import Blueprint,jsonify,request,g
import qiniu
from utils import restful, bbscache
import random, string
from tasks import send_email

bp = Blueprint('common', __name__, url_prefix='/c')


@bp.route('/')
def index():
    return 'common index'

# qiniu上传文件的接口
@bp.route('/uptoken/',methods=['GET','POST'])
def uptoken():
    access_key = '66CRz5bl1rPcfcBCA7JEO62fZut_BgGMi3pGF0kR'
    secret_kry = '3ERC5C8NogELpZlNyiQkPZDl2RYlzuP8HVO9Kwn4'
    q = qiniu.Auth(access_key,secret_kry)
    bucket = 'bbs-test'
    token = q.upload_token(bucket)
    return jsonify({'uptoken':token})

# 发送邮箱验证码
@bp.route('/email_captcha/')
def email_captcha():
    email = request.args.get('email')
    if not email:
        return restful.params_error('请输入邮箱！')
    source = list(string.ascii_letters)
    source.extend(map(lambda x: str(x), range(0, 10)))
    captcha = ''.join(random.sample(source, 6))
    # message = Message('BBS论坛邮箱验证码', recipients=[email], body='您修改邮箱的验证码是：%s，5分钟内有效' % captcha)
    # try:
    #     mail.send(message)
    # except:
    #     return restful.server_error()
    send_email.delay(subject='BBS论坛邮箱验证码', recipients=[email], body='您修改邮箱的验证码是：%s，5分钟内有效' % captcha)
    bbscache.set(email, captcha,timeout=60*5)
    return restful.success()
